package com.huangjue.backend.service.impl;

import com.huangjue.backend.entity.VideoFinish;
import com.huangjue.backend.mapper.VideoFinishMapper;
import com.huangjue.backend.service.VideoFinishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VideoFinishServiceImpl implements VideoFinishService {
    
    @Autowired
    private VideoFinishMapper videoFinishMapper;

    @Override
    public boolean markVideoWatched(Integer userId, Integer demoId, Integer videoId) {
        try {
            // 先检查是否已经记录过
            VideoFinish existing = videoFinishMapper.selectByUserAndVideo(userId, demoId, videoId);
            if (existing != null) {
                // 已经记录过了，返回成功
                return true;
            }
            
            // 创建新的观看记录
            VideoFinish videoFinish = new VideoFinish();
            videoFinish.setUserId(userId);
            videoFinish.setDemoId(demoId);
            videoFinish.setVideoId(videoId);
            
            int result = videoFinishMapper.insertVideoFinish(videoFinish);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean isVideoWatched(Integer userId, Integer demoId, Integer videoId) {
        try {
            VideoFinish videoFinish = videoFinishMapper.selectByUserAndVideo(userId, demoId, videoId);
            return videoFinish != null;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<VideoFinish> getWatchedVideos(Integer userId, Integer demoId) {
        try {
            return videoFinishMapper.selectByUserAndDemo(userId, demoId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean deleteVideoWatched(Integer userId, Integer demoId, Integer videoId) {
        try {
            int result = videoFinishMapper.deleteVideoFinish(userId, demoId, videoId);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
} 